import React, { useEffect, useState, useMemo } from "react";
import { useNavigate, useLocation } from "react-router";
import dayjs from "dayjs";
import zhCN from "antd/locale/zh_CN";
import {
  Button,
  Form,
  Input,
  Radio,
  ConfigProvider,
  Tag,
  Spin,
  message,
} from "antd";
import { useWatch } from "antd/es/form/Form";
import {
  DigitalEmployeeChoose,
  DigitalEmployeeset,
} from "@/api/Employee/index";
import type {
  DigitalEmployeeCategory,
  PostRequestParams,
} from "@/api/Employee/type.ts";
import { useDigitalEmployeeStore } from "@/store/employee";
import "./index.model.css";

import level1 from "@/assets/icon/level1.png";
import level2 from "@/assets/icon/level2.png";
import level3 from "@/assets/icon/level3.png";

const { TextArea } = Input;
const levelColorList = ["#c77221", "#c1cdd8", "#fbc54f"];

const FormDisabledDemo: React.FC<{
  form: any;
  iconPath: string | null;
  options: DigitalEmployeeCategory;
  workflows: string[];
  changelevel: string;
}> = ({ form, iconPath, changelevel, options, workflows }) => {
  return (
    <Form
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 14 }}
      layout="horizontal"
    >
      <Form.Item label="图标" name="icon">
        <div className="w-25 h-auto">
          {iconPath ? (
            <div className="relative">
              <img src={iconPath} alt="图标" />
              <img
                className="absolute top-5 right-0 w-7"
                src={changelevel}
                alt=""
              />
            </div>
          ) : (
            <></>
          )}
        </div>
      </Form.Item>

      <Form.Item label="工作流程" name="workflow" rules={[{ required: true }]}>
        <Radio.Group className="flex flex-wrap gap-4 custom-radio-group">
          {workflows.map((item) => (
            <Radio.Button key={item} value={item}>
              <span className="whitespace-nowrap">{item}</span>
            </Radio.Button>
          ))}
        </Radio.Group>
      </Form.Item>

      <Form.Item label="岗位" name="position" rules={[{ required: true }]}>
        <Radio.Group>
          <div className="">
            {options.position.map((item) => (
              <Radio key={item} value={item}>
                <span className="whitespace-nowrap">{item}</span>
              </Radio>
            ))}
          </div>
        </Radio.Group>
      </Form.Item>

      <Form.Item label="岗位职责" name="duty">
        <Input />
      </Form.Item>

      <Form.Item label="级别" name="level" rules={[{ required: true }]}>
        <Radio.Group>
          {options.grade.map((level, index) => (
            <Radio key={level} value={level}>
              <Tag color={levelColorList[index] || "#108ee9"}>{level}</Tag>
            </Radio>
          ))}
        </Radio.Group>
      </Form.Item>

      <Form.Item label="数字员工名称" name="name" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item
        label="运行状态"
        name="run_status"
        rules={[{ required: true }]}
      >
        <Radio.Group>
          {options.status.map((item) => (
            <Radio key={item} value={item}>
              {item}
            </Radio>
          ))}
        </Radio.Group>
      </Form.Item>

      <Form.Item
        label="系统平台"
        name="implement_method"
        rules={[{ required: true }]}
      >
        <Radio.Group>
          {options.method.map((item) => (
            <Radio key={item} value={item}>
              {item}
            </Radio>
          ))}
        </Radio.Group>
      </Form.Item>

      <Form.Item label="数字员工描述" name="description">
        <TextArea rows={3} />
      </Form.Item>
    </Form>
  );
};

const Information: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { state } = useLocation();
  const [loading, setLoading] = useState(true);
  const [allOptions, setAllOptions] = useState<
    Record<string, DigitalEmployeeCategory>
  >({});
  const [formOptions, setFormOptions] = useState<DigitalEmployeeCategory>({
    position: [],
    grade: [],
    status: [],
    method: [],
  });

  const getIconPath = useDigitalEmployeeStore((state) => state.getIconPath);

  const workflow = useWatch("workflow", form);
  const position = useWatch("position", form);
  const level = useWatch("level", form);
  const run_status = useWatch("run_status", form);

  const computedIconString = useMemo(() => {
    if (!workflow || !position || !run_status || !allOptions[workflow])
      return null;
    const category = allOptions[workflow];
    const workflowIndex = Object.keys(allOptions).indexOf(workflow);
    const positionIndex = category.position.indexOf(position);
    const run_statusIndex = category.status.indexOf(run_status); // 修正：用 status

    if ([workflowIndex, positionIndex, run_statusIndex].some((i) => i === -1))
      return null;
    return JSON.stringify({
      workflow: workflowIndex,
      position: positionIndex,
      run_status: run_statusIndex,
    });
  }, [workflow, position, run_status, allOptions]);

  const iconPath = useMemo(() => {
    return getIconPath(computedIconString as string);
  }, [computedIconString]);

  const changelevel = useMemo(() => {
    if (!workflow || !position || !level || !allOptions[workflow]) return null;

    const category = allOptions[workflow];
    const levelIndex = category.grade.indexOf(level);

    const levels = [level1, level2, level3];

    return levels[levelIndex] || null;
  }, [workflow, position, level, allOptions]);

  useEffect(() => {
    const fetchOptions = async () => {
      try {
        setLoading(true);
        const res = await DigitalEmployeeChoose();
        if (res.code === 1) {
          setAllOptions(res.data);
        } else {
          message.error("加载选项失败");
        }
      } catch (err) {
        message.error("接口调用异常");
      } finally {
        setLoading(false);
      }
    };
    fetchOptions();
  }, []);

  useEffect(() => {
    if (workflow && allOptions[workflow]) {
      setFormOptions(allOptions[workflow]);
    }
  }, [workflow, allOptions]);

  useEffect(() => {
    if (!state?.id) return;

    form.setFieldsValue({ workflow: state.workflow });

    const timeout = setTimeout(() => {
      form.setFieldsValue(state);
    }, 100);

    return () => clearTimeout(timeout);
  }, [state, formOptions]);

  useEffect(() => {
    if (computedIconString) {
      form.setFieldsValue({ icon: computedIconString });
    }
  }, [computedIconString]);

  useEffect(() => {
    if (Object.keys(allOptions).length === 0) return;

    const defaultWorkflow = Object.keys(allOptions)[0];
    const defaultOptions = allOptions[defaultWorkflow];

    form.setFieldsValue({
      workflow: defaultWorkflow,
      position: defaultOptions?.position[0],
      level: defaultOptions?.grade[0],
      run_status: defaultOptions?.status[0],
    });

    setFormOptions(defaultOptions); // 更新表单 options
  }, [allOptions]);

  const handleCreate = async () => {
    try {
      const values = await form.validateFields();
      const workflowIndex = Object.keys(allOptions).indexOf(values.workflow);
      const positionIndex = formOptions.position.indexOf(values.position);
      const run_statusIndex = formOptions.status.indexOf(values.run_status); // 修正

      const mappedValues: PostRequestParams = {
        ...values,
        icon: JSON.stringify({
          workflow: workflowIndex,
          position: positionIndex,
          run_status: run_statusIndex,
        }),
        id: state?.id,
      };

      const res = await DigitalEmployeeset(mappedValues);
      if (res.code === 1) {
        message.success(res.message);
        handleBack();
      } else {
        message.error(res.message);
      }
    } catch (err) {
      console.log("表单错误:", err);
    }
  };

  const handleBack = () => {
    form.resetFields();
    navigate(-1);
  };

  return (
    <div className="bg-white h-full page-container pt-8">
      <div className="text-5 mb-3 mt-2 flex items-center">
        <div className="w-[6px] h-[20px] bg-[#236BFF] mr-2 ml-2.5"></div>
        <span className="font-bold">数字员工创建</span>
      </div>

      <div className="bg-[#F5F5F5] rounded-20 min-h-150 p-8">
        <ConfigProvider
          locale={zhCN}
          theme={{
            components: {
              Form: {
                itemMarginBottom: 4,
                fontSize: 14,
              },
            },
          }}
        >
          {loading ? (
            <div className="flex justify-center py-20">
              <Spin size="large" />
            </div>
          ) : (
            <FormDisabledDemo
              form={form}
              iconPath={iconPath}
              options={formOptions}
              changelevel={changelevel}
              workflows={Object.keys(allOptions)}
            />
          )}
        </ConfigProvider>
      </div>

      <div className="flex items-center justify-center">
        <Button className="mt-8" onClick={handleBack}>
          返回
        </Button>
        {state?.change_type !== "view" && (
          <Button className="mt-8 ml-4" type="primary" onClick={handleCreate}>
            {state?.id ? "更新" : "创建"}
          </Button>
        )}
      </div>
    </div>
  );
};

export default Information;
